#include <SpatialIndex.h>
#include"libs.h"
using namespace SpatialIndex;
using namespace std;

extern const int N = 20000;
extern const double Inverse_A[DIMENSION+2][DIMENSION+2];
extern node Encryption_Point[N];
extern double theta[2*DIMENSION][DIMENSION+2][DIMENSION+2];

string baseName = "index";
IStorageManager* diskfile = 
  StorageManager::createNewDiskStorageManager(baseName, 4096);

StorageManager::IBuffer* file = 
  StorageManager::createNewRandomEvictionsBuffer(*diskfile, 10,
  false);

id_type indexIdentifier;
ISpatialIndex* tree =					\
  RTree::createNewRTree(*file, 0.7, 10000,		\
			10000, DIMENSION,		\
			SpatialIndex::RTree::RV_RSTAR,	\
			indexIdentifier);

double Cal_Result(double ma1[DIMENSION+2],double
ma2[DIMENSION+2][DIMENSION+2])
{
  int i,j;
  double temp[DIMENSION+2];
  for(i=0;i<DIMENSION+2;i++)
    {
      temp[i]=0;
      for(j=0;j<DIMENSION+2;j++)
	{
	  temp[i]+=ma1[j]*ma2[j][i];
	}
    }
  double ans=0;
  for(i=0;i<DIMENSION+2;i++)
    {
      ans+=temp[i]*ma1[i];
    }
  return ans;
}


void Pre1()
{
  FILE *fin=fopen("input1.txt","r");
  double plow[2], phigh[2], t;
  int i,j;
  printf("Pre starts\n");
  for(i=0;i<N;i++)
    {
      for(j=0;j<2;j++)
	{
	  fscanf(fin,"%lf",&t);
	  plow[j] = t;
	  phigh[j] = t;
	}
      //cout<<plow[0]<<' '<<plow[1]<<endl;
      Region r = Region(plow, phigh, 2);
      ostringstream os;
      os << r;
      string data = os.str();
      tree->insertData(data.size()+1, reinterpret_cast<const
		       byte*>(data.c_str()), r, i);
    }
  fclose(fin);
  printf("Pre ends\n");
}


// Insert data into RTree. 
bool insert() {
  double plow[DIMENSION+2],phigh[DIMENSION+2];
  int i,j;
  for(i=0;i<N;i++)
    {
      for(j=0;j<4;j++)
	{
	  plow[j]=Encryption_Point[i].coordinate[j];
	  phigh[j]=Encryption_Point[i].coordinate[j];
	}
      Region r = Region(plow, phigh, DIMENSION+2);
      ostringstream os;
      os << r;
      string data=os.str();
      //cout << "insert data point " << i << endl;
      tree->insertData(data.size()+1, reinterpret_cast<const
      byte*>(data.c_str()), r, i);
    }
  return true; 
}
